// pages/index/index.js
var template = require('../../global.js');
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        theme: "",
        searchShow: false,
        searchInput: "", //搜索框内容
        swiperImgUrls: [],  //滚动窗口
        searchSuggest: [],   //搜索建议，包括历史搜索 模糊搜索
        searchResultShow: false, //搜索结果
        searchResultes: [], //搜索结果
        amtSearchBtn: {},//动画
        bills: [], //歌单列表
        billSpinShow: true, //
        musicSpinShow: true,
        newSongs: [], //新歌榜
        h4: [{
            name: 'h4',
            attrs: {
                class: 'h4-class'
            },
            children: [{
                type: 'text',
                text: '推荐歌单'
            }]
        }]
    },

    //搜索框获得焦点
    inputFocus: function () {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease'
        })
        this.amtSearchBtn = animation;
        animation.translateX(-32).opacity(1).step();
        // 历史搜索
        var searchSuggest = [];
        try {
            var value = wx.getStorageSync('searchSuggest')
            if (value) {
                searchSuggest = value;
            }
        } catch (e) {
        }
        this.setData({
            searchShow: true,
            amtSearchBtn: animation.export(),
            searchSuggest: searchSuggest,
            searchResultShow: false
        })
    },

    // 搜索建议
    searchSuggest: function (e) {
        var input = e.detail.value;
        var that = this;
        if (input == "") {
            return
        }
        var success = function (res) {
            var data = res.data.result.allMatch;
            if (data.length > 0) {
                var searchSuggest = [];
                for (let i in data) {
                    searchSuggest[i] = data[i].keyword;
                }
                that.setData({
                    searchSuggest: searchSuggest
                })
            }
        }
        template.request("http://123.207.63.106:3000/search/suggest?keywords=" + input, "get", success);
    },

    // 搜索事件
    searchRequest: function (e) {
        this.setData({
            searchResultShow: true,

        })
        var input = "";
        // 输入框
        if (e.type == "confirm") {
            input = e.detail.value;
            this.setData({
                searchInput: input
            })
        }
        // 点击历史搜索
        else if (e.type == "tap") {
            input = e.target.dataset.name;
            this.setData({
                searchInput: input
            })
        }
        if (input == "") {
            template.message("empty");
            return
        }
        var searchSuggest = [];
        try {
            var value = wx.getStorageSync('searchSuggest')
            if (value) {
                searchSuggest = value;
            }
        } catch (e) {
        };
        // 不存在时返回-1
        var index = searchSuggest.indexOf(input);
        if (index != -1) {
            // 删除原本的，并插到头部
            searchSuggest.splice(index, 1);
            searchSuggest.unshift(input);
        } else {
            searchSuggest.unshift(input);
        }
        if (searchSuggest.length > 10) {
            searchSuggest.splice(0, 10);
        }
        wx.setStorage({
            key: 'searchSuggest',
            data: searchSuggest
        })
        var that = this;
        template.request("http://123.207.63.106:3000/search?keywords=" + input, "get", function (res) {
            if (res.data.code == 200) {
                var data = res.data.result.songs;
                var searchResultes = [];
                for (let i in data) {
                    searchResultes[i] = { id: "", musicName: "", singer: "" };
                    searchResultes[i].id = data[i].id;
                    if (data[i].name == null) {
                        searchResultes[i].musicName = "未知歌曲";
                    } else {
                        searchResultes[i].musicName = data[i].name;
                    }
                    searchResultes[i].singer = data[i].artists[0].name + "-" + data[i].album.name;
                }
                that.setData({
                    searchResultes: searchResultes
                })
            }
        })
    },


    //取消搜索按钮
    searchDialogHide: function () {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease'
        })
        this.amtSearchBtn = animation;
        animation.translateX(32).opacity(0).step();
        this.setData({
            amtSearchBtn: animation.export(),
            searchShow: false,
            searchInput: "",
        })
    },

    // 删除历史搜索
    deleteHistory: function (e) {
        var hSearch = e.target.dataset.name;
        var searchSuggest = this.data.searchSuggest;
        var index = searchSuggest.indexOf(hSearch);
        searchSuggest.splice(index, 1);
        this.setData({
            searchSuggest: searchSuggest
        })
        wx.setStorage({
            key: 'searchSuggest',
            data: searchSuggest,
        })
    },

    // 点击歌曲
    playMusic: function (e) {
        var songId = e.currentTarget.dataset.songid;
        // template.request("http://123.207.63.106:3000/music/url?id="+songId,"get",function(res){
        //     console.log(res);
        // })
        var musicName = e.currentTarget.dataset.musicname;
        this.setData({
            searchInput: musicName
        })
        wx.navigateTo({
            url: '../music/music?musicId=' + songId,
        })
        // this.setData({
        //     currentSwiper: "musicSwiper"
        // })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        // 轮播图
        // var imgs = ["../../image/scrollPic1.jpg", "../../image/scrollPic2.jpg", "../../image/scrollPic3.jpg"];
        var imgs = ["http://p1.music.126.net/DsHUvMQ5fesuGf8rrC47hg==/109951163381420990.jpg", "http://p1.music.126.net/qOYGDNKsAkHMtvPCnXsnpQ==/109951163381419672.jpg", "http://p1.music.126.net/LfyInu6we_Dq3rFJjJc1rg==/109951163381409810.jpg"];
        this.setData({
            swiperImgUrls: imgs,
        })
        // template.request("https://music.163.com/weapi/personalized/newsong?csrf_token=e286a8731787970a18c2f4589a495ad0", "post", function (res) {
        //     console.log(res);
        // })
        // 歌单
        template.request("http://123.207.63.106:3000/personalized", "get", function (res) {
            if (res.data.code == 200) {
                var data = res.data.result;
                var bills = [];
                for (let i in data) {
                    if (i >= 6) {
                        break;
                    }
                    bills[i] = { imgSrc: "", des: "" };
                    bills[i].imgSrc = data[i].picUrl;
                    bills[i].des = data[i].name;
                }
                that.setData({
                    bills: bills,
                    billSpinShow: false
                })
            }
        })

        // 最新音乐
        template.request("http://123.207.63.106:3000/personalized/newsong", "get", function (res) {
            if (res.data.code == 200) {
                var data = res.data.result;
                var newSongs = [];
                for (let i in data) {
                    newSongs[i] = { id: "", musicName: "", singer: "" };
                    newSongs[i].id = data[i].id;
                    newSongs[i].musicName = data[i].song.name;
                    newSongs[i].singer = data[i].song.artists[0].name
                }
                that.setData({
                    newSongs: newSongs,
                    musicSpinShow: false
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.videoCtx = wx.createVideoContext('myVideo')
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var theme = app.globalData.theme;
        this.setData({
            theme: theme
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})